define(['moment'], function () {
    return ['$scope', '$rootScope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater',
        function ($scope, $rootScope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater) {

            $scope.init = function () {
                $scope.printData = {
                    item_no: '', 
                    item_name: '',
                    wo_no: '', 
                    plot_no: '',
                    Copies: '1',
                    CopyMode: '1'
                };
                $scope.printMode = [
                    { code: '0', label: $filter('translate')('B1201.MPCount_none') },
                    { code: '1', label: $filter('translate')('B1201.MPCount_same') },
                    { code: '2', label: $filter('translate')('B1201.MPCount_diff') }
                ];
                $scope.printDataList = [];
                $scope.selectedList = [];
                $scope.printList = []; // 列印詳情
                $scope.isMobile = window.cordova != undefined;
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            // 取得產品編號
            $scope.loadItemNo = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 'opm_product_no_info_get',
                    pageRecord: 50,
                    condition: [
                        {name:$filter('translate')('common.queryList.item_c'), column_name:'ProductNo', query_mode:'2', value: $scope.printData.item_no}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.item_c'), code:'product_no'},
                        {label:$filter('translate')('common.queryList.item_n'), code:'product_name'}
                    ],
                    setCondition:function(conditions){
                        conditions.push(
                            {column_name:'IssueState', query_mode:'0', value:'2', merge_condition_model:'AND' },
                            {column_name:'CurVersion', query_mode:'0', value:'1', merge_condition_model:'AND' },
                        );
                        return conditions;
                    },
                    selectCode: $scope.printData.item_no || '',
                    confirm : function(selectItem){
                        $scope.printData.item_no = selectItem.product_no;
                        $scope.printData.item_name = selectItem.product_name;
                    }
                });
            };

            //取得工單編號
            $scope.loadWoNo = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 'opm_wo_no_info_get',
                    pageRecord: 50,
                    condition: [
                        {name:$filter('translate')('common.queryList.wo_c'), column_name:'A.MONo', query_mode:'2', value:$scope.printData.wo_no}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.wo_c'), code:'wo_no'}
                    ],
                    setCondition:function(conditions){
                        if($scope.printData.item_no){
                            conditions.push(
                                {column_name:'A.PRODUCTNO', query_mode:'2', value: $scope.printData.item_no, merge_condition_model:'AND'}
                            );
                        }
                        return conditions;
                    },
                    selectCode: $scope.printData.wo_no || '',
                    confirm : function(selectItem){
                        $scope.printData.wo_no = selectItem.wo_no;
                    }
                });
            };

            // 输入打印份数
            $scope.input_print_qty = function (event, Copies) {
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function (num, dialogNum) {
                    if (num == 0) {
                        $rootScope.showAlert($filter('translate')('B1201.msg.column02'));
                        return;
                    }
                    angular.element(target).removeClass('is-focus');
                    $scope.printData.Copies = num;
                    dialogNum.hide();
                },
                function (dialogNum) {
                    angular.element(target).removeClass('is-focus');
                    dialogNum.hide();
                },
                {
                    defaultNum: $scope.printData.Copies,
                    decimal: false
                });
            };

            // 输入单份包装数量
            $scope.input_perQty = function (event, item) {
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function (num, dialogNum) {
                    if (num == 0) {
                        $rootScope.showAlert($filter('translate')('B1201.msg.column02'));
                        return;
                    }
                    angular.element(target).removeClass('is-focus');
                    $scope.selectedList.forEach(s => {
                        s.mpqty = num;
                    });
                    dialogNum.hide();
                },
                function (dialogNum) {
                    angular.element(target).removeClass('is-focus');
                    dialogNum.hide();
                },
                {
                    defaultNum: item.mpqty,
                    decimal: false
                });
            };

            // 更改打印份数标签
            $scope.changeType = function (type) {
                $scope.printData.CopyMode = type;
                if (type == '1'){
                    $scope.printData.Copies = '1';
                }
            }

            // 打印模式
            $scope.loadMPCountList = function (it) {
                $rootScope.showSelect({
                    title: $filter('translate')('B1201.MPCount_mode'),
                    label: 'label',
                    code: 'code',
                    selectCode: it.mpcount,
                    list: $scope.printMode,
                    confirm: function (item, d) {
                        d.hide();
                        it.mpcount = item.code;
                        it.MPCountDes = item.label;
                    }
                });
            }

            // 查詢標籤打印資料
            $scope.search = function () {
                var query_condition_info = [];
                if($scope.printData.item_no){
                    query_condition_info.push({column_name: "b.PRODUCTNO", query_mode: "2", value: $scope.printData.item_no, merge_condition_model: "AND"});
                } 
                if($scope.printData.wo_no){
                    query_condition_info.push({column_name: "b.mono", query_mode: "2", value: $scope.printData.wo_no, merge_condition_model: "AND"});
                } 
                if($scope.printData.plot_no){
                    query_condition_info.push({column_name: "a.lotno", query_mode: "2", value: $scope.printData.plot_no, merge_condition_model: "AND"});
                }
                
                //  20230103 modify by shiwl for#  0154529: 力邦合信，正式区。标签补印问题 
                if(query_condition_info.length == 0) {
                    $scope.$root.showAlert($filter('translate')('B1201.msg.column08'));
                    return false;
                }  

                $MMWService.pageNumberInfoGet({
                    page_mode: 'print_data_info_get',
                    query_condition_info: query_condition_info
                }, function(itemList){
                    if(itemList && itemList.length > 0){
                        $scope.printDataList = itemList;
                    } else {
                        $scope.printDataList = [];
                        $scope.selectedList = [];
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });
            };

            // 點選 + 號，選擇產品到下方區域
            $scope.itemCheck = function (index, data) {
                if($scope.selectedList.length === 0)
                {
                    addTarget(data);
                }
                else
                {

                    // 20220802 modify by shiwl for# 0135742: 标签打印能重复查询添加 
                    let flag = false;
                    if( $scope.selectedList.length>0){
                        $scope.selectedList.forEach((item)=>{
                            if(item.plot_no == data.plot_no ){
                                flag = true;
                            }
                         })
                     if(flag){
                           
                        var msg = data.plot_no + $filter('translate')('B1201.msg.column07')
                        $scope.$root.showAlert(msg);
                      } else {
                            // 如果下方區域已經有選擇的產品時，之後在上方要選擇產品就必須與下方已選擇的產品的工單符合
                        if($scope.selectedList[0].wo_no === data.wo_no)
                         {
                            addTarget(data);
                         }
                        else
                         {
                            // 與已選擇的產品的工單不符合，無法往下新增！
                            $scope.$root.showAlert($filter('translate')('B1201.msg.column01'));
                         }
                      }
                    }
                } 
            };

            // 點選 + 號，選擇產品到下方區域
            function addTarget(data){
                data.checked = !data.checked;
                data.barcode_qty = data.qty;
                let match = $scope.printMode.filter(f => f.code == data.mpcount);
                if (match.length > 0){
                    data.MPCountDes = match[0].label;
                }
                $scope.selectedList.push(data);
                $scope.printDataList.splice($scope.printDataList.indexOf(data), 1);
            };
            
            // 點選 - 號，移動產品回上方區域
            $scope.returnTarget = function (index, data) {
                data.checked = !data.checked;
                $scope.printDataList.push(data);
                $scope.selectedList.splice($scope.selectedList.indexOf($scope.selectedList[index]), 1);
            };

            // 更改進入條碼數量
            $scope.changeBarcodeQty = function(event, item){
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function(num, calcDialog)
                { 
                    if(+(num) === 0){
                        // 數量不能為 0！
                        $scope.$root.showAlert($filter('translate')('B1201.msg.column02'));
                    } else if(+(num) > +(item.qty)){
                        // 數量不能大於原本的條碼數量！
                        $scope.$root.showAlert($filter('translate')('B1201.msg.column03'));
                    } else if(+(num) <= +(item.qty)){
                        angular.element(target).removeClass('is-focus');
                        calcDialog.hide();
                        item.barcode_qty = num;
                    } else {
                        // 數量不能為空或是數字以外的結果！
                        $scope.$root.showAlert($filter('translate')('B1201.msg.column04'));
                    }
                },
                function(calcDialog)
                {
                    angular.element(target).removeClass('is-focus');
                    calcDialog.hide();
                },
                {
                    defaultNum : item.barcode_qty,
                    decimal : false
                });
            };

            // 送出打印
            $scope.print = function () {
                if ($scope.printData.CopyMode == '3'){
                    // 最小包装数打印检验数量大于0
                    let mpqtyArr = $scope.selectedList.filter(s => s.mpqty == '' || s.mpqty <= 0);
                    if (mpqtyArr.length > 0){
                        $scope.$root.showAlert($filter('translate')('B1201.msg.column05'));
                        return;
                    }
                    // 校验必须选择相同barcode或者不同barcode
                    let printModeArr = $scope.selectedList.filter(s => s.mpcount != '1' && s.mpcount != '2');
                    if (printModeArr.length > 0){
                        $scope.$root.showAlert($filter('translate')('B1201.msg.column06'));
                        return;
                    }
                }
                var isStoragePlot = false;
                for(var i = 0; i < $scope.selectedList.length; i++){
                    if($scope.selectedList[i].stocklotno == '1')
                    {
                        isStoragePlot = true;
                        break;
                    }
                };

                if(isStoragePlot) {
                    $mdDialog.dialog('module/moduleB/program/B12/B1201/B1201_StoragePlot.tmp.html', function(dialog) {
                        return {
                            storage_plot: $scope.selectedList[0].wo_no, // 預設工單號，因為工單號都會是一樣的，所以取第一筆即可
                            back: function() {
                                dialog.hide();
                            },
                            clearPlot: function() {
                                dialog.storage_plot = '';
                            },
                            confirm: function() {
                                dialog.hide();
                                printDataProcess(dialog.storage_plot);
                            }
                        };
                    });
                } else {
                    printDataProcess();
                }
            };

            // 打印服務
            var pdf_url;
            function printDataProcess(storage_plot){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.print_data_process',
                    content : {
                        print_data: $scope.selectedList,
                        storage_plot: storage_plot || '',
                        CopyMode: $scope.printData.CopyMode,
                        Copies: $scope.printData.Copies
                    },
                    success : function(data){

                        for(var i = 0; i < $scope.selectedList.length; i++){
                            $scope.printList.push({
                                printNo: data.Barcode,
                                printType: '3' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
                            });
                        }

                        if(data.runcard_pdf_get.length == 0 && data.command_lines.length == 0)
                        {
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        } 
                        else
                        {
                            // 執行標籤列印 
                            if(data.command_lines && data.command_lines.length > 0)
                            {
                                printTag(data.command_lines, 0, data.runcard_pdf_get);
                            } 
                            // 執行 PDF列印
                            if(data.runcard_pdf_get && data.runcard_pdf_get.length > 0)
                            {
                                // 20201121 modify by 外包 for M#80272: 增加不同的标签可以多条打印的功能
                                let tempRuncardPdf = [];
                                data.runcard_pdf_get.forEach(r => {
                                    if (r.printCount > 1){
                                        for(var i = 0; i < r.printCount; i++){
                                            tempRuncardPdf.push({
                                                url_pdf: r.url_pdf,
                                                width: r.width,
                                                height: r.height,
                                                printCount: 1
                                            });
                                        }
                                    }else {
                                        tempRuncardPdf.push(r);
                                    }
                                });
                                printBatch(tempRuncardPdf, 0);
                            }
                            $scope.selectedList = [];
                        }
                    }
                });
            };

            // 條碼列印
            var isError = false;
            function printTag(commandLines, index, runcard_pdf_get){
                if(commandLines && index < commandLines.length){
                    if(window.nodeRequire){
                        var exec = window.nodeRequire('child_process').exec;
                        exec(commandLines[index], function(error, stdout, stderr){
                            if(error){
                                isError = true;
                                $rootScope.showAlert($filter('translate')('B1201.msg.cantprint'));
                            }
                            index = index +1;
                            printTag(commandLines, index, runcard_pdf_get);
                        });
                    }
                } else {
                    if(!isError){
                        isError = false;
                        $scope.$root.showToast($filter('translate')('common.msg.success'));
                        if(runcard_pdf_get && runcard_pdf_get.length === 0){
                            printWiplogProcess();
                        } 
                    }
                }
            };

            // 批量打印
            function printBatch(runcard_pdf_get, index){
                if (index < runcard_pdf_get.length){
                    pdf_url = runcard_pdf_get[index].url_pdf;
                    if(pdf_url.indexOf('http://') == -1){
                        pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
                    }
                    var width = runcard_pdf_get[index].width;
                    var height = runcard_pdf_get[index].height;
                    print(pdf_url, width, height, function callback(){
                        index = index + 1;
                        printBatch(runcard_pdf_get, index);
                    });
                    
                }
            };
            
            // PDF列印
            function print(pdf_url, width, height, callback){
                if(window.nodeRequire){
                    var sumatraPDF = window.nodeRequire('sumatra-pdf');
                    if(sumatraPDF){
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try{
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            RuncardPath = remote.app.getAppPath();
                        }catch(e){
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if(!fs.existsSync(RuncardPath)){
                            fs.mkdirSync(RuncardPath);
                        }

                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        fs.readdirSync(RuncardPath, (err, files) => {
                            if (err) {
                                console.log(err);
                            }
                            //listing all files using forEach
                            files.forEach((file) => {
                                // Do whatever you want to do with the file
                                fs.unlink(RuncardPath + '/' + file, (err) => {
                                    if (err) {
                                        console.debug(err);
                                    }
                                })
                            });
                        })
    
                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                            $rootScope.showLoading();
                            // 20201110 modify by WeiTing for M#80602 - 不跳列印介面，直接使用預設列印機進行列印(printToDefault)。
                            var _fn = sumatraPDF.printToDefault;
                            _fn({
                                path: dist_path,
                                settings: width > height ? 'landscape' : '',
                                success:function(){
                                    callback();
                                    printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                    $rootScope.hideLoading();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                },
                                error:function(error){
                                    // 20201104 modify by WeiTing for M#77013 - 不清楚為何列印後，實際列印一張紙和輸入成 PDF檔案都會執行 error 區域，所以目前也先列印完成後，把列印詳情回送給後台做記錄。
                                    printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                    $rootScope.hideLoading();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                    //console.error(error);
                                }
                            });
                        });
                    } else {
                        window.frames['kmi-pdf-panel'].pdf_print();
                    }
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            };
            
            // 列印完成後，需把列印詳情回送給後台做記錄
            function printWiplogProcess(){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.print_wiplog_process',
                    content : {
                        printList: $scope.printList
                    },
                    success : function(){
                        $scope.printList = [];
                    }
                });
            }

        }
    ];
});
